package com.lvchen.common;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.lvchen.common.utils.UIHelper;
import com.lvchen.network.OkhttpClient;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by 律晨 on 2018/5/24.
 */
public class MyApplication extends Application{

    public static MyApplication instance;
    private SharedPreferences sharedPreferences;
    private static Context context;
    public final static int CONNECT_TIMEOUT = 40;
    public final static int READ_TIMEOUT = 40;
    public final static int WRITE_TIMEOUT = 40;

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        instance = this;

        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);

        try {
            if(OkhttpClient.isDebug){
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                        .build();
                OkHttpUtils.initClient(okHttpClient);

            }else {
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                        .proxy(Proxy.NO_PROXY)//不设置代理  防止抓包
                        .build();
                OkHttpUtils.initClient(okHttpClient);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        File cacheDir = StorageUtils.getOwnCacheDirectory(instance, "imageloader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(instance).
                threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCacheExtraOptions(200, 200)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new WeakMemoryCache())
                .diskCache(new UnlimitedDiskCache(cacheDir))
                .denyCacheImageMultipleSizesInMemory()// 当同一个uri获取不同大小的图片，缓存到内存时，只缓存一个，默认会缓存多个不同大小的图片
                .build();
        ImageLoader.getInstance().init(config);


    }

    public static MyApplication getInstance() {
        return instance;
    }

    //弹出吐司
    public void showToast(final String string) {
        UIHelper.toast(MyApplication.this, string, false);
    }

    //弹出吐司
    public void showToast(final String string, boolean status) {
        UIHelper.toast(MyApplication.this, string, status);
    }

    //得到userid
    public String getUserid() {
        String userid = sharedPreferences.getString("userid", "");
        return userid;
    }

    //得到sessionkey
    public String getSessionkey() {
        String sessionkey = sharedPreferences.getString("sessionkey", "");
        return sessionkey;
    }

    //设置cookie
    public void SetCookie(String cookie) {
        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putString("cookie", cookie);
        editor.commit();
    }

    //得到cookie
    public String getCookie() {
        String cookie = sharedPreferences.getString("cookie", "");
        return cookie;
    }

    /*start app前后台的切换响应的方法*/
    public static boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) MyApplication.instance.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = MyApplication.instance.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    public static void appResume() throws UnsupportedEncodingException, JSONException {
        if (MyApplication.getInstance().isAppOnForeground()) {
            enterForeground();
            foreground();
        }
    }

    public static void appStop() {
        if (!MyApplication.getInstance().isAppOnForeground()) {
            enterBackground();
        }
    }

    public static boolean foreground() throws UnsupportedEncodingException, JSONException {
        return true;
    }

    public static void enterForeground() throws UnsupportedEncodingException, JSONException {
        System.out.println("进入前台");

    }

    private static void enterBackground() {
        System.out.println("进入后台");
    }

    /**
     * 获取进程号对应的进程名
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

}
